package com.tz.shop.seckill.consumer;

import com.alibaba.fastjson.JSONObject;
import com.tz.shop.common.config.RabbitService;
import com.tz.shop.model.activity.SeckillGoods;
import com.tz.shop.seckill.mapper.SeckillGoodsMapper;
import com.tz.shop.seckill.pojo.SeckillOrder;
import com.tz.shop.seckill.pojo.UserRecode;
import net.sf.jsqlparser.util.deparser.DeleteDeParser;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @author 铁铸
 * @create 2021-07-17 8:38
 */

/**
 * 秒杀下单监听类
 */
@Component
public class SeckillOrderAddConsumer {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    @Autowired
    private RabbitService rabbitService;

    /**
     * 监听排队消息进行秒杀下单
     * @param msg
     */
    @RabbitListener(queues = "seckill_queue")
    public void addOrder(String msg){

        //将消息类型转换为排队信息
        UserRecode userRecode = JSONObject.parseObject(msg, UserRecode.class);
        //获取用户的用户标识name，时间和商品id
        String username = userRecode.getUsername();

        //这里没做处理重复排队之前，需要验证用户是否有未支付的订单，有的话就不能往下走
        //需要改变订单状态

        //下面就需要生成订单了
        String time = userRecode.getTime();
        String goodsId = userRecode.getGoodsId();
        //校验商品,检测商品库存是否为空
        SeckillGoods seckillGoods = (SeckillGoods) redisTemplate.boundHashOps("SeckillGoods_" + time).get(goodsId);
        //秒杀商品不为空时
        if (seckillGoods != null){
            //商品类型转换
            //Integer stockCount = seckillGoods.getStockCount();
            //这个是把数据取出来
            Object o = redisTemplate.boundListOps("seckillGoodsQueue_" + goodsId).rightPop();
            //判断库存
            if (o != null){
                //构建订单信息，生成一个订单需要订单号，商品id，商品购买数量，金额，用户名，时间，还有状态
                SeckillOrder seckillOrder = new SeckillOrder();
                //创建订单消息，设定一个订单号
                seckillOrder.setId(UUID.randomUUID().toString().replace("-",""));
                seckillOrder.setGoodsId(goodsId);   //商品id
                seckillOrder.setNum(userRecode.getNum());  //商品数量
                //计算一下金额
                seckillOrder.setMoney(userRecode.getNum()*seckillGoods.getCostPrice().doubleValue()+"");
                seckillOrder.setUserId(username);  //用户id
                seckillOrder.setCreateTime(userRecode.getCreateTime()); //时间
                seckillOrder.setStatus("0");
                //将信息存入redis中
                //这个是每个用户的id都不一样，所以将买过的商品根据商品id存到这个以用户名为key的里面
                redisTemplate.boundHashOps("SeckillOrder_"+username).put(seckillOrder.getId(),seckillOrder);
                //更新库存，存在超卖问题-----------TODO
                //生成订单就将库存数量-1,更新库存数量
                Long stockNum = redisTemplate.boundHashOps("SeckillGoodsStockNum").increment(goodsId, -1);
                seckillGoods.setStockCount(stockNum.intValue());
                if (stockNum>0){
                    redisTemplate.boundHashOps("SeckillGoods_" + time).put(goodsId, seckillGoods);
                }
                else {
                    //售罄处理,将redis中商品的数据清除掉
                    redisTemplate.boundHashOps("SeckillGoods_" + time).delete(goodsId);
                    //将商品的数据同步到数据库中去
                    seckillGoodsMapper.updateById(seckillGoods);
                }
                //更新一下排队的状态
                userRecode.setStatus(2); //变为待支付
                userRecode.setMoney(Float.valueOf(seckillOrder.getMoney())); //价钱显示出来
                userRecode.setOrderId(seckillOrder.getId()); //得有订单的id
                //更新用户的排队状态
                redisTemplate.boundValueOps("SeckillStatus_" + username).set(userRecode);
                //发送一个延迟消息记录订单的有效期倒计时-----todo
                rabbitService.sendMessage("seckill_dead_exchange",
                        "seckill.dead.order",
                        JSONObject.toJSONString(seckillOrder),
                        "300");
                //结束
                return;
            }
        }
        //商品售罄，修改队伍状态，下单失败
        userRecode.setStatus(3);
        //更新用户排队状态
        redisTemplate.boundValueOps("SeckillStatus_" + username).set(userRecode);
        //重复排队标识删除
        redisTemplate.delete("SeckillUserQueue_" + username);
        //结束
        return;
    }


}
